package com.bingxue.edu.management.shop.service;

import com.bingxue.edu.common.enums.OrderStatusEnum;
import com.bingxue.edu.management.shop.mapper.OrderItemMapper;
import com.bingxue.edu.management.shop.model.entity.OrderItem;
import com.bingxue.edu.framework.mybatis.base.BaseService;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.bingxue.edu.management.shop.model.entity.table.OrderItemTableDef.ORDER_ITEM;
import static com.bingxue.edu.management.shop.model.entity.table.OrderTableDef.ORDER;

/**
 * 订单课程项业务实现类
 *
 * @author panbo
 * @since 2024/08/27 14:28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderItemService extends BaseService<OrderItemMapper, OrderItem> {

    public List<OrderItem> getListByOrderId(String orderId) {
        return this.queryChain().where(ORDER_ITEM.ORDER_ID.eq(orderId)).list();
    }

    /**
     * 根据指定班级的订单项数量
     */
    public long countValidOrderItemByClassId(String classId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(ORDER_ITEM.DEFAULT_COLUMNS)
                .from(ORDER_ITEM)
                .leftJoin(ORDER).on(ORDER_ITEM.ORDER_ID.eq(ORDER.ID))
                .where(ORDER_ITEM.CLASS_ID.eq(classId))
                .and(ORDER.PAY_OFF.eq(false))
                .and(ORDER.CANCEL_TIME.isNull()); // 未支付的订单
        return this.count(queryWrapper);
    }

    public boolean exitsPendingPayOrderItemByClassId(String studentId, String classId) {
        return this.queryChain()
                .leftJoin(ORDER).on(ORDER_ITEM.ORDER_ID.eq(ORDER.ID))
                .where(ORDER_ITEM.CLASS_ID.eq(classId))
                .and(ORDER.STUDENT_ID.eq(studentId))
                .and(ORDER.STATUS.in(OrderStatusEnum.PENDING, OrderStatusEnum.PAYING))
                .count() > 0;
    }

    /**
     * 根据班级id和学生id获取订单项
     */
    public OrderItem getByClassIdAndStudentId(String classId, String studentId) {
        return this.queryChain()
                .where(ORDER_ITEM.CLASS_ID.eq(classId))
                .and(ORDER_ITEM.STUDENT_ID.eq(studentId))
                .limit(1)
                .one();
    }
}
